from __future__ import division

import pygame

def draw_edges(node, surface, ignore, weightings):
    for neighbour in node.neighbours - ignore:
        pygame.draw.line(surface, (int(96 + (255-96) * (weightings[node] + weightings[neighbour]) / 2), 0, 0), node.position, neighbour.position)

def draw_node(node, surface):        
    pygame.draw.circle(surface, (255, 0, 0), node.position, 2, 1)

def draw_tower(tower, surface):
    if tower.target:
        pygame.draw.circle(surface, (0, 255, 0), tower.position, 2, 1)
    else:
        pygame.draw.circle(surface, (128, 128, 0), tower.position, 5)

def draw_creep(creep, surface):
    x, y = creep.position
    
    c = max(0, int(creep.health / 100 * 255))
     
    pygame.draw.rect(surface, (c, c, c), (x - 4, y - 4, 8, 8))

def draw_map(map, weights, surface):
    ignore = set()
    
    for node in map.graph.nodes:
        draw_edges(node, surface, ignore, weights) 
        ignore.add(node)
        
        if len(node.neighbours) == 0:
            draw_node(node, surface)

def draw_paths(map, paths, surface):
    for i, spawn in enumerate(map.spawns):
        prev = spawn
        current = paths[spawn]
        
        c = i / (len(map.spawns)-1)
        
        while current != prev:
            pygame.draw.line(surface, (0, int(5 * c + 50), 100), prev.position, current.position, 3)
            prev = current
            current = paths[current]
    
    pygame.draw.circle(surface, (255, 0, 255), map.objective.position, 4)

def draw_targeting(game, surface):
    for tower in game.towers:
        pygame.draw.circle(surface, (0, 255, 96), tower.position, tower.range, 1)
        
        for node in game.towerindex[tower]:
            if game.creepindex.index[node]:
                pygame.draw.circle(surface, (255, 255, 0), node.position, 1)
    
        if tower.target is not None:
            pygame.draw.line(surface, (0, 192, 0), tower.position, tower.target.position, 3)
            
            x,y = tower.target.position
            
            pygame.draw.rect(surface, (0, 255, 0), (x - 4, y - 4, 8, 8), 1)
    
    for node, creeps in game.creepindex.index.iteritems():
        if creeps:      
            pass#pygame.draw.circle(surface, (128, 255, 128), node.position, 1)
    
class GameView(object):
    def __init__(self, game, size):
        self.game = game
        self.size = size
        
        self.map_render = pygame.Surface(size)
        draw_map(self.game.map, self.game.pathing.weights["test"], self.map_render)
        draw_paths(self.game.map, self.game.pathing.paths["test"], self.map_render)
           
    def draw(self, surface):
        surface.blit(self.map_render, (0, 0))
        
        for unit in self.game.creeps:
            draw_creep(unit, surface)

        draw_targeting(self.game, surface)
            
        for tow in self.game.towers:
            draw_tower(tow, surface)
    